﻿using System;
using System.Collections.Generic;
using System.Text;
using PluginCore;
using System.IO;
using PluginCore.Helpers;
using PluginCore.Utilities;
using WeifenLuo.WinFormsUI.Docking;
using System.Drawing;
using System.Windows.Forms;
using PluginCore.Managers;
using System.Collections;
using MUnitGenerator.Actions;
using ProjectManager.Controls.TreeView;
using PluginCore.FRService;
using System.ComponentModel;

namespace MUnitGenerator
{
    public delegate void ProcessEndHandler(string result);

    public class PluginMain : IPlugin
    {
        private string author = "expl";
        private string description = "This is my first plugin";
        private string guid = "42ac7fab-421b-1f38-a985-72a0sd34f7sf";
        private string help = "www.flashdevelop.org/community/";
        private string name = "MUnitGenerator";
        private Settings settingObject;

        #region Required Properties

        /// <summary>
        /// Author of the plugin
        /// </summary>
        public string Author
        {
            get { return author; }
        }

        /// <summary>
        /// Description of the plugin
        /// </summary>
        public string Description
        {
            get { return description; }
        }

        /// <summary>
        /// GUID of the plugin
        /// </summary>
        public string Guid
        {
            get { return guid; }
        }

        /// <summary>
        /// Web address for help
        /// </summary>
        public string Help
        {
            get { return help; }
        }

        /// <summary>
        /// Name of the plugin
        /// </summary>
        public string Name
        {
            get { return name; }
        }

        /// <summary>
        /// Object that contains the settings
        /// </summary>
        [Browsable(false)]
        public object Settings
        {
            get { return settingObject; }
        }

        #endregion

        #region Required Methods

        /// <summary>
        /// Handles the incoming events
        /// </summary>
        public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority)
        {
            switch (e.Type)
            {
                case EventType.Command:
                    DataEvent de = e as DataEvent;
                    string action = de.Action;
                    if (action == "ProjectManager.TreeSelectionChanged")
                    {
                        ProjectTreeView tree = sender as ProjectTreeView;

                        ToolStripMenuItem item = new ToolStripMenuItem("Create TestCase...");
                        item.Click += new CreateTestCaseAction(tree.Project, tree.SelectedPath).ExecuteHandler;

                        ToolStripItemCollection items = (sender as Control).ContextMenuStrip.Items;
                        items.Add("-");
                        items.Add(item);
                    }
                    break;
                case EventType.ProcessEnd:
                    string result = (e as TextEvent).Value;
                    if (processEndEvent != null)
                    {
                        processEndEvent(result);
                    }
                    break;
            }
        }

        /// <summary>
        /// Disposes the plugin
        /// </summary>
        public void Dispose()
        {
            SaveSettings();
        }

        /// <summary>
        /// Initializes the plugin
        /// </summary>
        public void Initialize()
        {
            String dataPath = Path.Combine(PathHelper.DataDir, name);
            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            settingFilename = Path.Combine(dataPath, "Settings.fdb");
            this.image = PluginBase.MainForm.FindImage("100");

            EventManager.AddEventHandler(this, EventType.Command | EventType.ProcessEnd);

            LoadSettings();
            CreateMenuItem();
        }

        #endregion

        #region Custom Methods

        private bool IsWizardTemplate(string templateFile)
        {
            return templateFile != null && File.Exists(templateFile + ".wizard");
        }

        private void LoadSettings()
        {
            this.settingObject = new Settings();
            if (!File.Exists(this.settingFilename))
            {
                this.SaveSettings();
            }
            else
            {
                Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject);
                this.settingObject = (Settings)obj;
            }
            if (this.settingObject.HaXePath == null) // default values
            {
                string eVariable = System.Environment.GetEnvironmentVariable("HAXEPATH");
                settingObject.HaXePath = eVariable ?? @"C:\Program Files\Motion-Twin\haxe";
            }
            if (this.settingObject.ReportClientClass == null)
            {
                settingObject.ReportClientClass = "massive.munit.client.PrintClient";
            }
        }

        /// <summary>
        /// Saves the plugin settings
        /// </summary>
        private void SaveSettings()
        {
            ObjectSerializer.Serialize(this.settingFilename, this.settingObject);
        }

        public event ProcessEndHandler processEndEvent;

        private string settingFilename;
        private Image image;

        private void CreateMenuItem()
        {
            ToolStripMenuItem viewMenu = (ToolStripMenuItem)PluginBase.MainForm.FindMenuItem("ToolsMenu");

            viewMenu.DropDownItems.Add(
                new ToolStripMenuItem(
                    "Run all munit tests", this.image,
                    new RunAllTestsAction(this, settingObject).ExecuteHandler,
                    MUnitGenerator.Settings.RunAllTestsShortcut
                )
            );
            PluginBase.MainForm.IgnoredKeys.Add(MUnitGenerator.Settings.RunAllTestsShortcut);

            viewMenu.DropDownItems.Add(
                new ToolStripMenuItem(
                    "Run current munit test", this.image,
                    new RunCurrentTestAction(this, settingObject).ExecuteHandler,
                    MUnitGenerator.Settings.RunCurrentTestShortcut
                )
            );
            PluginBase.MainForm.IgnoredKeys.Add(MUnitGenerator.Settings.RunCurrentTestShortcut);
        }

        #endregion

        /// <summary>
        /// Api level of the plugin
        /// </summary>
        public Int32 Api
        {
            get { return 1; }
        }

    }
}
